<template>
  <div class="agent-detail-page" v-loading="loading">
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-button @click="$router.go(-1)" text>
            <i class="el-icon-arrow-left"></i>
            返回
          </el-button>
          <div class="agent-header-info">
            <h1>{{ agent?.name }}</h1>
            <el-tag :type="getStatusType(agent?.status)" size="small">
              {{ getStatusText(agent?.status) }}
            </el-tag>
          </div>
        </div>
        <div class="header-actions">
          <el-button @click="startChat" type="primary">
            <i class="el-icon-chat-line-round"></i>
            开始对话
          </el-button>
          <el-dropdown @command="handleAction">
            <el-button>
              更多操作
              <i class="el-icon-arrow-down"></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="duplicate">复制</el-dropdown-item>
                <el-dropdown-item command="share">分享</el-dropdown-item>
                <el-dropdown-item divided command="delete" class="danger">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <div class="page-content" v-if="agent">
      <div class="detail-layout">
        <!-- 主要信息 -->
        <div class="main-content">
          <!-- 基本信息卡片 -->
          <el-card class="info-card">
            <div class="agent-info">
              <div class="agent-avatar">
                <img v-if="agent.avatar" :src="agent.avatar" alt="智能体头像" />
                <i v-else class="el-icon-cpu default-avatar"></i>
              </div>
              <div class="agent-details">
                <h2>{{ agent.name }}</h2>
                <p class="agent-description">{{ agent.description }}</p>
                <div class="agent-meta">
                  <div class="meta-item">
                    <i class="el-icon-collection-tag"></i>
                    <span>{{ agent.agent_type_name }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-user"></i>
                    <span>{{ agent.creator_name }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-time"></i>
                    <span>{{ formatDate(agent.created_at) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 系统提示词 -->
          <el-card>
            <template #header>
              <h3>系统提示词</h3>
            </template>
            <div class="prompt-content">
              <pre>{{ agent.system_prompt }}</pre>
            </div>
          </el-card>

          <!-- 配置信息 -->
          <el-card>
            <template #header>
              <h3>AI配置</h3>
            </template>
            <div class="config-grid">
              <div class="config-item">
                <label>AI模型</label>
                <span>{{ agent.model_name }}</span>
              </div>
              <div class="config-item">
                <label>创造性参数</label>
                <span>{{ agent.temperature }}</span>
              </div>
              <div class="config-item">
                <label>最大令牌数</label>
                <span>{{ agent.max_tokens }}</span>
              </div>
              <div class="config-item">
                <label>可见性</label>
                <span>{{ agent.is_public ? '公开' : '私有' }}</span>
              </div>
            </div>
          </el-card>

          <!-- 知识域和能力 -->
          <el-card v-if="agent.knowledge_domains?.length || agent.capabilities?.length">
            <template #header>
              <h3>知识域和能力</h3>
            </template>
            <div class="tags-section">
              <div v-if="agent.knowledge_domains?.length" class="tag-group">
                <h4>知识领域</h4>
                <div class="tags">
                  <el-tag 
                    v-for="domain in agent.knowledge_domains" 
                    :key="domain"
                    type="primary"
                    class="tag-item"
                  >
                    {{ domain }}
                  </el-tag>
                </div>
              </div>
              <div v-if="agent.capabilities?.length" class="tag-group">
                <h4>能力标签</h4>
                <div class="tags">
                  <el-tag 
                    v-for="capability in agent.capabilities" 
                    :key="capability"
                    type="success"
                    class="tag-item"
                  >
                    {{ capability }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 侧边栏 -->
        <div class="sidebar">
          <!-- 统计信息 -->
          <el-card class="stats-card">
            <template #header>
              <h3>使用统计</h3>
            </template>
            <div class="stats-list">
              <div class="stat-item">
                <span class="stat-label">对话次数</span>
                <span class="stat-value">{{ agent.usage_count }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">平均评分</span>
                <span class="stat-value">
                  {{ agent.rating > 0 ? agent.rating.toFixed(1) : '暂无' }}
                  <i v-if="agent.rating > 0" class="el-icon-star-on"></i>
                </span>
              </div>
              <div class="stat-item">
                <span class="stat-label">评分数量</span>
                <span class="stat-value">{{ agent.rating_count }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">最后使用</span>
                <span class="stat-value">
                  {{ agent.last_used_at ? formatDate(agent.last_used_at) : '从未使用' }}
                </span>
              </div>
            </div>
          </el-card>

          <!-- 快速操作 -->
          <el-card class="actions-card">
            <template #header>
              <h3>快速操作</h3>
            </template>
            <div class="quick-actions">
              <el-button @click="startChat" type="primary" style="width: 100%;">
                <i class="el-icon-chat-line-round"></i>
                开始对话
              </el-button>
              <el-button @click="viewConversations" style="width: 100%;">
                <i class="el-icon-chat-dot-round"></i>
                查看对话历史
              </el-button>
              <el-button @click="editAgent" style="width: 100%;">
                <i class="el-icon-edit"></i>
                编辑智能体
              </el-button>
            </div>
          </el-card>

          <!-- 评分组件 -->
          <el-card class="rating-card" v-if="!isOwner">
            <template #header>
              <h3>为此智能体评分</h3>
            </template>
            <div class="rating-section">
              <el-rate 
                v-model="userRating.rating" 
                :max="5" 
                show-score 
                text-color="#ff9900"
              />
              <el-input
                v-model="userRating.comment"
                type="textarea"
                :rows="3"
                placeholder="分享您的使用体验..."
                style="margin-top: 12px;"
              />
              <el-button 
                @click="submitRating" 
                type="primary" 
                :loading="submittingRating"
                style="width: 100%; margin-top: 12px;"
              >
                提交评分
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { agentApi } from '@/services/api'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()

const loading = ref(false)
const submittingRating = ref(false)
const agent = ref(null)

const userRating = reactive({
  rating: 0,
  comment: ''
})

const isOwner = computed(() => {
  return agent.value?.creator === userStore.user?.id
})

onMounted(() => {
  loadAgentDetail()
})

const loadAgentDetail = async () => {
  loading.value = true
  try {
    const response = await agentApi.getAgent(route.params.id)
    agent.value = response.data
  } catch (error) {
    console.error('Failed to load agent detail:', error)
    appStore.showError('加载智能体详情失败')
    router.push('/agents')
  } finally {
    loading.value = false
  }
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    draft: 'info',
    training: 'warning',
    inactive: 'danger',
    error: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    active: '活跃',
    draft: '草稿',
    training: '训练中',
    inactive: '停用',
    error: '错误'
  }
  return statusMap[status] || status
}

const startChat = () => {
  router.push(`/chat/${agent.value.id}`)
}

const viewConversations = () => {
  router.push(`/conversations?agent=${agent.value.id}`)
}

const editAgent = () => {
  router.push(`/agents/${agent.value.id}/edit`)
}

const handleAction = async (command) => {
  switch (command) {
    case 'edit':
      editAgent()
      break
    case 'duplicate':
      appStore.showInfo('复制功能开发中...')
      break
    case 'share':
      appStore.showInfo('分享功能开发中...')
      break
    case 'delete':
      await handleDelete()
      break
  }
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除智能体 "${agent.value.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    await agentApi.deleteAgent(agent.value.id)
    appStore.showSuccess('智能体删除成功')
    router.push('/agents')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete agent:', error)
      appStore.showError('删除智能体失败')
    }
  }
}

const submitRating = async () => {
  if (userRating.rating === 0) {
    appStore.showWarning('请选择评分')
    return
  }
  
  submittingRating.value = true
  try {
    await agentApi.rateAgent(agent.value.id, userRating)
    appStore.showSuccess('评分提交成功')
    // 重新加载智能体详情以更新评分
    await loadAgentDetail()
    // 重置评分表单
    userRating.rating = 0
    userRating.comment = ''
  } catch (error) {
    console.error('Failed to submit rating:', error)
    appStore.showError('提交评分失败')
  } finally {
    submittingRating.value = false
  }
}
</script>

<style scoped lang="scss">
.agent-detail-page {
  min-height: 100vh;
  background: #f5f7fa;
}

.page-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  max-width: 1200px;
  margin: 0 auto;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.agent-header-info {
  display: flex;
  align-items: center;
  gap: 12px;
  
  h1 {
    margin: 0;
    font-size: 1.5rem;
    color: var(--el-text-color-primary);
  }
}

.header-actions {
  display: flex;
  gap: 12px;
}

.page-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.detail-layout {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card {
  :deep(.el-card__body) {
    padding: 30px;
  }
}

.agent-info {
  display: flex;
  gap: 20px;
}

.agent-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  background: var(--el-color-primary-light-9);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .default-avatar {
    font-size: 32px;
    color: var(--el-color-primary);
  }
}

.agent-details {
  flex: 1;
  
  h2 {
    margin: 0 0 12px 0;
    font-size: 1.5rem;
    color: var(--el-text-color-primary);
  }
}

.agent-description {
  margin: 0 0 16px 0;
  color: var(--el-text-color-regular);
  line-height: 1.6;
}

.agent-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  
  i {
    font-size: 16px;
  }
}

.prompt-content {
  pre {
    margin: 0;
    white-space: pre-wrap;
    word-wrap: break-word;
    font-family: inherit;
    line-height: 1.6;
    color: var(--el-text-color-primary);
  }
}

.config-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  
  label {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    font-weight: 500;
  }
  
  span {
    font-size: 16px;
    color: var(--el-text-color-primary);
  }
}

.tags-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tag-group {
  h4 {
    margin: 0 0 12px 0;
    font-size: 16px;
    color: var(--el-text-color-primary);
  }
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  margin: 0;
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stats-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  &:last-child {
    border-bottom: none;
  }
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.stat-value {
  font-size: 14px;
  color: var(--el-text-color-primary);
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.rating-section {
  text-align: center;
}

:deep(.danger) {
  color: var(--el-color-danger);
}

@media (max-width: 992px) {
  .detail-layout {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    gap: 15px;
    padding: 15px 0;
  }
  
  .agent-info {
    flex-direction: column;
    text-align: center;
  }
  
  .agent-meta {
    justify-content: center;
  }
}
</style>